<?php
/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/8/26
 * Time: 18:08
 * Comment: '接口参数公用处理类'
 */

namespace App\Params;

use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use Illuminate\Support\Facades\Validator;

class BaseParam
{
    protected function fill(bool $sign = false)
    {
        $rules = $this->rules();
        // 获取所有参数
        $data = $sign ? request()->input('data', []) : request()->input();
        // 校验参数
        $validator = Validator::make($data, $rules,$this->message());

        if($validator->fails()) {
            $validatorMsg = $validator->getMessageBag()->getMessages();

            $errorMsg = $validatorMsg[array_keys($validatorMsg)[0]][0];

            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => $errorMsg]);
        }
        // 动态赋值
        collect($data)->map(function ($val, $key) {
            if(property_exists($this, $key)) {
                $this->{$key} = $val;
            }
        });

        return $this;
    }

    /**
     * 获取校验对象
     * @return static
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-08-26 18:09
     */
    public static function create()
    {
        return (new static())->fill();
    }

    /**
     * 校验签名对象
     * @return BaseParam
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-08-26 18:09
     */
    public static function createData()
    {
        return (new static())->fill(true);
    }

    /**
     *  参数规则校验
     * @return array
     * @author shen.zk
     * @date 2023-08-26 18:10
     */
    public function rules()
    {
        return [];
    }

    /**
     * 参数规则错误提示
     * @return array
     * @author shen.zk
     * @date 2023-08-26 18:10
     */
    public function message()
    {
        return [];
    }

    /**
     * 参数转换为数组
     * @return array
     * @author shen.zk
     * @date 2023-08-26 18:10
     */
    public function toArray()
    {
        $arr = [];
        foreach ($this as $field => $value) {
            if(property_exists($this, $field)) {
                $arr[$field] = $value;
            }
        }
        return $arr;
    }
}
